//
//  WebViewController.swift
//  zhengwutong
//
//  Created by Bernie on 16/8/25.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
import JavaScriptCore
import SnapKit
import SwiftyJSON
import WebKit
class WebViewController: UIViewController,UINavigationControllerDelegate,  UIGestureRecognizerDelegate ,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler{
    
    private var webview: WKWebView!
    var image:UIImage?
    var link:URL!
    let animateView = UIActivityIndicatorView(style: .gray)
    var webJsFunCall:(String,AnyObject)->() = {_,_ in}
    var newsId:String?
    var isFav = false
    var cancelAction = {}
    var isAllowShare = true
    var teamJSON:JSON?
    var header:[String : String]?
    let userController = WKUserContentController()
    /// 是否隐藏导航条
    var isHideNavibar = false
    /// 默认是0什么功能都没有，1是督查督办
    var type = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        let wbConfig = WKWebViewConfiguration()
        wbConfig.mediaPlaybackAllowsAirPlay = true;
        wbConfig.mediaPlaybackRequiresUserAction = false;
        // inject some Javascript into our page before it even loads...
        let scriptSource = "console.log('Hi from the iOS app hosting this page...'); window.hostedByWkWebView=true;";
        let userScript = WKUserScript(source: scriptSource, injectionTime: .atDocumentStart, forMainFrameOnly: true)

        wbConfig.userContentController.addUserScript(userScript)
        wbConfig.userContentController.add(self, name: "iosBridge")
        
        
        webview = WKWebView(frame: .zero, configuration: wbConfig)
        webview.uiDelegate = self
        webview.navigationDelegate = self
        if #available(iOS 13.0, *) {
            webview.backgroundColor = .systemBackground
        } else {
            // Fallback on earlier versions
            webview.backgroundColor = .white
        }
        view.backgroundColor = webview.backgroundColor
        self.view.addSubview(webview)
        var request = URLRequest(url: link)
        if let h = header{
            request.allHTTPHeaderFields = h
        }
        webview.load(request)
        self.view.addSubview(animateView)
        self.view.removeConstraints(self.view.constraints)
        self.webview.snp.makeConstraints {(make) in
            make.edges.equalToSuperview()
        }
        animateView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: 45, height: 45))
            make.center.equalToSuperview()
        }
        animateView.startAnimating()
        
        
        self.changeTopConstraint()
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        UIApplication.shared.sendAction(#selector(self.resignFirstResponder), to: nil, from: nil, for: nil)
    }
    deinit {
        userController.removeScriptMessageHandler(forName: "iosBridge")
    }
    //MARK: - CUSTOM METHODS
    @objc func back() {
        if self.webview.canGoBack{
            self.webview.goBack()
        }else{
            self.goBack()
        }
    }
    override func goBack(){
        UIApplication.shared.sendAction(#selector(self.resignFirstResponder), to: nil, from: nil, for: nil)
        self.navigationController?.popViewController()
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        if (self.title ?? "").isEmpty{
            webView.evaluateJavaScript("document.title") { (text, erorr) in
                if let t = text as? String{
                    self.title = t
                }
            }
        }
        animateView.removeFromSuperview()

        if webView.canGoBack{
            let bt = UIButton(type: .system)
            bt.setTitle(" 返回", for: .normal)
            bt.setImage(UIImage(named: "contactBack"), for: .normal)
            bt.tintColor = .default
            bt.addTarget(self, action: #selector(back), for: .touchUpInside)
            self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: bt),UIBarButtonItem(image: UIImage(named: "news_close"), style: .done, target: self, action: #selector(goBack))]
        }else{
            let bt = UIButton(type: .system)
            bt.setTitle(" 返回", for: .normal)
            bt.setImage(UIImage(named: "contactBack"), for: .normal)
            bt.tintColor = .default
            bt.addTarget(self, action: #selector(back), for: .touchUpInside)
            self.navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: bt)]
        }
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        animateView.removeFromSuperview()
    }
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if (navigationAction.targetFrame == nil) {
            webView.load(navigationAction.request)
        }
        decisionHandler(.allow)
    }
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        
        let frameInfo = navigationAction.targetFrame;
        if (!(frameInfo?.isMainFrame ?? false)) {
            webView.load(navigationAction.request)
        }
        return nil
    }
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "iosBridge"{
            /// webjs调用方法 window.webkit.messageHandlers.iosBridge.postMessage("invitedList");
            if let funcstr = message.body as? String{
                if funcstr.hasPrefix("{"){
                    let para = JSON(funcstr.toJsonObject() ?? [:])
                }else if funcstr == "closePage"{
                    goBack()
                }
            }
        }
    }
}
